package com.jiaxu.wifimusic;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import android.os.Handler;
import android.util.Log;

import java.util.List;

public class MusicService extends Service {

    public static MediaPlayer player;
    Handler handler ;
    List<MusicInfo> playList;
    public int currentPosition=0;
    PlayController playController;
    public MusicService() {
    }

    @Override
    public void onCreate() {
        super.onCreate();
        handler = new Handler();
        playList = MainActivity.playList;
        player = new MediaPlayer();
        playController= new PlayController(player);
        player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                try {
                    MusicService.this.playController.nextMusic(playList, currentPosition);
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        int action = intent.getIntExtra("action", -1);
        String url = intent.getStringExtra("url");

        switch (action) {
            case MainActivity.PLAYORPAUSE:
                if(playController.isPause())
                    playController.play();
                else
                    playController.pause();
                break;
            case MainActivity.NEXT:
                try {
                    MusicService.this.playController.nextMusic(playList, currentPosition);
                } catch (Exception e) {
                    e.printStackTrace();
                }

                break;
            case MainActivity.CHANGE:
                playController.changeMusic(url);
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    public class Mybinder extends Binder {
        private int progress = 100;
        private int duration;
        public int getProgress() {
            progress = player.getCurrentPosition();
            return progress;
        }
        public int getDuration() {
            duration = player.getDuration();
            return duration;
        }
        public void setPosition(int positon){
            currentPosition = positon;
        }
        public int getPosition(){
            return currentPosition;
        }
        public void setProgress(int progress) {
            player.seekTo(progress);
        }
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new Mybinder();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        player.stop();
        player.release();
    }
}
